package com.zenchn.aspect;

import com.zenchn.aspect.service.BuildSaveLogService;
import com.zenchn.aspect.utils.LogAspectUtils;
import com.zenchn.model.TSysAccount;
import com.zenchn.model.TSysLoginAccessRecord;
import com.zenchn.utils.CommonUtils;
import com.zenchn.utils.IPUtils;
import com.zenchn.utils.Ip2RegionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 *  登录访问记录 异步保存AOP
 * @author panbingqi
 * @date 2021-06-01
 */
@Aspect
@Order(3)
@Component
public class LoginAccessAspect {

    @Resource
    private BuildSaveLogService buildSaveLogService;

    @Pointcut("execution(public * com.zenchn.controller.LoginController.login(..))")
    public void accessRecord() {
    }

    @AfterReturning(returning = "ret", pointcut = "accessRecord()")
    public void doAfterReturning(Object ret)  {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            //登录操作完成后保存访问记录
            //接收到请求，记录请求内容
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            assert attributes != null;
            HttpServletRequest request = attributes.getRequest();
            String ip = IPUtils.getRealIP(request);
            final TSysAccount currAccount = (TSysAccount) subject.getPrincipal();

            TSysLoginAccessRecord record = new TSysLoginAccessRecord();

            record.setRecordId(CommonUtils.randomUUID());
            record.setAccessIp(ip);
            record.setAccessLocation(Ip2RegionUtils.getCleanAddress(ip));
            record.setAccessTime(LocalDateTime.now());
            record.setLoginAccount(currAccount.getAccount());
            record.setLoginAccountId(currAccount.getAccountId());
            record.setLoginRealName(currAccount.getRealName());
            record.setOperatingSystem(LogAspectUtils.getOsName(request));
            record.setBrowser(LogAspectUtils.getBrowserName(request)+"("+LogAspectUtils.getBrowserVersion(request)+")");

            buildSaveLogService.saveLoginAccessRecord(record);
        }
    }



}
